package com.aphrodite.ui.widgets.browser;

import java.io.IOException;

import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;

import com.aphrodite.xml.XMLReader;

/**
 * A href element
 * 
 * @author kentelt
 * 
 */
final class A extends BrowserElement {
	static Font hyperLink = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_UNDERLINED, Font.SIZE_SMALL);
	String link;

	String text;

	A() {

	}

	A(String text) {
		this.text = text;
		width = hyperLink.stringWidth(text);
		height = hyperLink.getHeight();
		color = 0x0000ff;
	}

	void draw(Graphics g) {
		if (text != null) {
			g.setFont(hyperLink);
			g.setColor(color);
			g.drawString(text, x, y, 0);
		}

	}

	/**
	 * Returns a domain from a link. for instance it would return
	 * "www.comcast.com" for link http://www.comcast.com/test.html
	 * 
	 * @return
	 */
	private String getDomain() {
		String url = HTMLBrowser.currentUrl;
		url = url.substring(7);
		int index = url.indexOf('/');
		url = url.substring(0, (index > 0) ? index : url.length());
		return url;

	}

	private void getLink() {
		/*
		 * ifthere is a fwd slash add the link to the domain directly if not add
		 * it to the current url
		 */
		if (link.startsWith("/")) {
			String domain = getDomain();
			StringBuffer buf = new StringBuffer("http://").append(domain).append(link);
			link = buf.toString();
		} else {
			link = (HTMLBrowser.currentUrl.endsWith("/")) ? HTMLBrowser.currentUrl + link : HTMLBrowser.currentUrl
					+ '/' + link;
		}
	}

	// void process(XmlParser parser, ParseEvent pe, Attribute attr) {
	// attr = pe.getAttribute("href");
	// if (attr != null) {
	// link = attr.getValue();
	// if (!link.startsWith("http:")) {
	// /* append the URL appropriately */
	// getLink();
	// }
	// System.out.println("link found " + link);
	// }
	// }

	void process(XMLReader reader) {
		try {
			link = reader.getAttribute("href");
			text = reader.readText();
			if (!link.startsWith("http:")) {
				/* append the URL appropriately */
				getLink();
			}
			System.out.println("link found " + link);
		} catch (IOException e) {
			System.out.println(e);
		}

	}

}
